package com.lc.cn.managersys.dao.example;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import com.lc.cn.managersys.common.JdbcTemplate;
import com.lc.cn.managersys.common.Page;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.lc.cn.managersys.model.example.UserForm;


/**
 * example
 * @author luo_guang
 *
 */
@Repository
public class UserDao  {

	private static final String GET_USERS = "select * from t_user where id=?";
	private static final String DELETE_USER = "DELETE FROM t_user where id = 5"; 
	private static final String COUNT_USER = "SELECT * FROM t_user WHERE name like ? and address like ?"; 
	private static final String LIST_USERS = "select name, psd from t_user WHERE name like ? and address like ?";
	private static final String INSERT_USER = "insert into t_user(name, psd, address)values(?,?,?)";
	@Autowired
	private JdbcTemplate jdbcTemplate = null;

	@SuppressWarnings("unchecked")
	public UserForm getUser() {
		return (UserForm)(jdbcTemplate.queryForObject(GET_USERS, new Object[] {8}, new RowMapper() {

			@Override
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				UserForm user = new UserForm();
				user.setId(rs.getInt("id"));
				user.setAddress(rs.getString("address"));
				user.setName(rs.getString("name"));
				user.setPsd(rs.getString("psd"));
				return user;
			}
			
		}));
	}
	
	public void deleteUser() {
		jdbcTemplate.execute(DELETE_USER);
	}
	
	public int countUser() {
		return jdbcTemplate.queryForCount(COUNT_USER, new Object[] {"%lg2%", "%杭州2%"});
	}
	
	@SuppressWarnings("unchecked")
	public List listUsers() {
		return jdbcTemplate.queryForList(LIST_USERS, new Object[] {"%lg2%", "%杭州2%"});
	}
	
	public long insertUser() {
		return jdbcTemplate.insert(INSERT_USER, new Object[] {"lg2", "22", "杭州2"});
	}
	
	public Page pageUser() {
		Page page = new Page(1, 5);
		return jdbcTemplate.queryForPage(page, LIST_USERS, new Object[] {"%lg2%", "%杭州2%"});
	}
}
